package com.software.library_conquer;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.qozix.tileview.TileView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends TileViewActivity {

    //    ArrayList<Point> first;
    static HashMap<Integer, ArrayList<Point>> floormap;
    SlidingMenu slide_menu;
    ArrayList<Point> marklist;
    PopupWindow popupWindow;
    int floor = 1;
    Point lastPosition;

    private String[] names = { "Choose Density", "Low", "Medium", "High"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        floor = getIntent().getIntExtra("floor", 1);
        // multiple references
        initData();

        TileView tileView = getTileView();
        TextView titleText = getTitleText();

        // size of original image at 100% scale
        tileView.setSize(4096, 4096);

        // detail levels
        switch (floor){
            case 1:
                tileView.addDetailLevel(1.000f, "map/%col%_%row%.jpg", "samples/1ceng.jpg");
                break;
            case 2:
                tileView.addDetailLevel(1.000f, "map/%col%_%row%.jpg", "samples/2ceng.jpg");
                break;
            case 3:
                tileView.addDetailLevel(1.000f, "map/%col%_%row%.jpg", "samples/3ceng.jpg");
                break;
            case 4:
                tileView.addDetailLevel(1.000f, "map/%col%_%row%.jpg", "samples/4ceng.jpg");
                break;
            case 5:
                tileView.addDetailLevel(1.000f, "map/%col%_%row%.jpg", "samples/5ceng.jpg");
                break;
        }
        titleText.setText("Floor "+floor);
        setmap(floor);

        // allow scaling past original size
        tileView.setScaleLimits(0, 2);

        // lets center all markers both horizontally and vertically
        tileView.setMarkerAnchorPoints(-0.5f, -0.5f);

        // frame the troll
        frameTo(500, 500);

        // scale down a little
        tileView.setScale(0.5);

        View container = getLayoutInflater().inflate(R.layout.mymenu, null);
        ListView gridView = (ListView)container.findViewById(R.id.menu_gridView);
        gridView.setAdapter(new Mainadapter(this));
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 1:
                        lastPosition.density = 0;
                        break;
                    case 2:
                        lastPosition.density = 1;
                        break;
                    case 3:
                        lastPosition.density = 2;
                        break;
                }
                if (position > 0) {
                    setmap(floor);
                    popupWindow.dismiss();
                    update();
                    Toast.makeText(getApplicationContext(), "更新位置成功", Toast.LENGTH_SHORT).show();
                }
            }
        });

        popupWindow = new PopupWindow(container, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(R.style.popwindow);

        Task task = new Task();
        task.execute(floor);
        initSlidingMenu();
    }


    class Mainadapter extends BaseAdapter{

        LayoutInflater inflater = null;
        Context mContext;

        public Mainadapter(Context context){
            inflater = LayoutInflater.from(context);
            this.mContext = context;
        }

        @Override
        public int getCount() {
            return names.length;
        }

        @Override
        public Object getItem(int position) {
            return names[position];
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.mymenu_item, null);
            TextView textView = (TextView)view.findViewById(R.id.menu_item);
            textView.setText((String)getItem(position));
            return view;
        }
    }

    private void initData(){
        if (floormap == null){
            floormap = new HashMap<>();
            LibraryActivity manager = LibraryActivity.getManager();
            floormap.put(1, manager.getFirst());
            floormap.put(2, manager.getSecond());
            floormap.put(3, manager.getThird());
            floormap.put(4, manager.getForth());
            floormap.put(5, manager.getFifth());
        }
    }

    public void fresh(View view){
        Task task = new Task();
        task.execute(floor);
    }

    public void update(){
        new Thread(){
            @Override
            public void run(){
                LibraryActivity.getManager().update(lastPosition.objectID, lastPosition.density);
            }
        }.start();
    }

    private void setmap(int floor){
        // individual markers
//        getTileView().removeAllViews();
        marklist = floormap.get(floor);
        for (int i = 0; i < marklist.size(); i++) {
            Point point = marklist.get(i);
            switch(point.density){
                case 0:
                    placeMarker(R.mipmap.location_low, point);
                    break;
                case 1:
                    placeMarker(R.mipmap.location_medium, point);
                    break;
                case 2:
                    placeMarker(R.mipmap.location_high, point);
                    break;
            }
        }
    }
    private void placeMarker(int resId, Point point) {
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(resId);
        imageView.setTag(point);
        imageView.setOnClickListener(markerClickListener);
        getTileView().addMarker(imageView, point.x, point.y);
    }

    private View.OnClickListener markerClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // get reference to the TileView
            TileView tileView = getTileView();
            // we saved the coordinate in the marker's tag
            lastPosition = (Point) view.getTag();
            // lets center the screen to that coordinate
            tileView.slideToAndCenter(lastPosition.x, lastPosition.y);
            // create a simple callout
            SampleCallout callout = new SampleCallout(view.getContext(), lastPosition);
            // add it to the view tree at the same position and offset as the marker that invoked it
            tileView.addCallout(callout, lastPosition.x, lastPosition.y, -0.5f, -1.0f);
            // a little sugar
            callout.transitionIn();
            showmenu(popupWindow);
        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
//        showmenu(popupWindow);
        return true;
    }

//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }
    protected void initSlidingMenu() {
        slide_menu = new DrawerView(this).initSlidingMenu();
    }

    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(slide_menu.isMenuShowing()){// ||side_drawer.isSecondaryMenuShowing()){
                slide_menu.showContent();
            }else if (popupWindow.isShowing())
                popupWindow.dismiss();
            else {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "再按一次退出",
                            Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                } else {
                    finish();
                }
            }
            return true;
        }
        //拦截MENU按钮点击事件，让他无任何操作
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            if(!slide_menu.isMenuShowing())// || !side_drawer.isSecondaryMenuShowing())
                slide_menu.showMenu();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onMenu(View view){
        if (slide_menu.isMenuShowing())
            slide_menu.showContent();
        else
            slide_menu.showMenu();
    }

    class Task extends AsyncTask<Integer, Integer, Integer>{

        @Override
        protected Integer doInBackground(Integer... params) {
            int index = params[0];
            LibraryActivity.getManager().freshdensity(floormap.get(index), index);
            return null;
        }
        @Override
        protected void onPostExecute(Integer res){
            setmap(floor);
            Toast.makeText(MainActivity.this, "刷新成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            Task task = new Task();
            task.execute(floor);
            return true;
        }

        if (id == android.R.id.home) {
          if (slide_menu.isMenuShowing())
            slide_menu.showContent();
          else
            slide_menu.showMenu();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
